<?php

class Kd_Template {

    protected $registeredBlocks = array();
    protected $blockContents = array();
    protected $currentBlock = '';
    protected $layout = NULL;
    protected $arguments = array();

    public function __construct() {
    	$this->arguments = array(
    		'page'=>Kd_Web::getPage(),
    		'router'=>Kd_Web::getRouter(),
    	);
    	$this->initialize();
    }
    
    protected function initialize(){}

    public function __get($name) {
        $result = '';
        $name = Kd_Util_String::wordToUnderline($name);
        if (isset($this->arguments[$name])) {
            $result = $this->arguments[$name];
        }

        return is_string($result) ? urldecode($result) : $result;
    }

    public function __call($name, $arguments) {
        $tmplMethod = 'tmpl' . ucfirst($name);
        $args = array($this);
        $args = array_merge($args, $arguments);
        return call_user_func_array($tmplMethod, $args);
    }

    public function getArgments() {
        return $this->arguments;
    }

    public function assign($name, $value) {
        $this->arguments[$name] = $value;
        return $this;
    }

    public function assignMulti(array $values) {
        $this->arguments = array_merge($this->arguments, $values);
        return $this;
    }

    public function getLayout() {
        return $this->layout;
    }

    public function setLayout($value) {
        $this->layout = $value;
    }

    public function startBlock($name = 'default') {
        $this->currentBlock = $name;
        ob_start();
        return $this;
    }

    public function endBlock() {
        $this->registeredBlocks[$this->currentBlock] = ob_get_clean();
        return $this;
    }

    protected function setBlockContents(array $blocks) {
        $this->blockContents = $blocks;
        return $this;
    }

    protected function renderBlock($name = 'default') {
        if (isset($this->blockContents[$name])) {
            return $this->blockContents[$name];
        }
        return '';
    }

    public function render($path) {
        ob_start();
        include $path;
        $content = ob_get_clean();

        if (!is_null($this->layout)) {
            if (!empty($this->blockContents)) {
                $this->registeredBlocks = array_merge($this->blockContents, $this->registeredBlocks);
            }
            $template = new Kd_Template();
            $content = $template->setBlockContents($this->registeredBlocks)->render($this->layout);
        }

        return $content;
    }

}

